<template>
  <div class="icon-selector">
    <a-select
      v-model="selectedIcon"
      :style="{ width: '100%' }"
      allow-search
      placeholder="请选择图标"
      :filter-option="filterOption"
      @change="handleIconChange"
    >
      <template #prefix>
        <component :is="getIcon(selectedIcon)" v-if="selectedIcon" />
      </template>
      <a-option v-for="icon in iconList" :key="icon.name" :value="icon.name">
        <div class="flex items-center gap-2">
          <component :is="icon.component" />
          <span>{{ icon.name }}</span>
          <span class="text-gray-400 text-sm">{{ icon.label }}</span>
        </div>
      </a-option>
    </a-select>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import * as Icons from '@arco-design/web-vue/es/icon'
import { getIcon } from '@/composables/useIcons'
import type { SelectOptionData } from '@arco-design/web-vue'
import { iconChineseMap } from '@/config/icon'

const props = defineProps<{
  modelValue?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const selectedIcon = computed({
  get: () => props.modelValue || '',
  set: (value: string) => emit('update:modelValue', value),
})

// 获取所有图标并添加中文描述
const iconList = computed(() => {
  return Object.entries(Icons)
    .filter(([key]) => key.startsWith('Icon'))
    .map(([key, component]) => {
      const name = key
        .replace(/([A-Z])/g, '-$1')
        .toLowerCase()
        .replace(/^-/, '')
      return {
        name,
        component,
        label: iconChineseMap[name] || '', // 添加中文标签
      }
    })
})

// 修改筛选方法的类型定义
const filterOption = (inputValue: string, option: SelectOptionData) => {
  const input = inputValue.toLowerCase()
  return (
    (typeof option.value === 'string' && option.value.toLowerCase().includes(input)) ||
    (option.label && option.label.includes(input)) ||
    false
  )
}

const handleIconChange = (
  value:
    | string
    | number
    | boolean
    | Record<string, unknown>
    | (string | number | boolean | Record<string, unknown>)[],
) => {
  selectedIcon.value = value as string
}
</script>
